/**
 * @description 动态 services
 */

const {Dynamic,User,DynamicLike} = require('../db/model/index')
const Sequelize = require('sequelize')

/**
 * @description 创建动态
 * @param {*} param0 
 */
async function createDynamic({
    title,
    url,
    userId,
    type
}) {
    const result = await Dynamic.create({
        title,
        url,
        userId,
        type
    })
    const data = result.dataValues
    return data
}

/**
 * @description 查询动态列表
 * @param {number} pageIndex 查询的页数
 * @param {number} pageSize 每次要查询的数量
 * @param {number} userId 要查询的用户ID 不填查询所有
 */
async function getDynamicList({pageIndex=0,pageSize,userId}) {
    const whereData={}
    if(userId){
        whereData.userId = userId
    }
    const result =await Dynamic.findAndCountAll({
        // limit: pageSize,//每次查询多少条
        offset:pageSize * pageIndex,//跳过多少条
        attributes:['id','title','url','likeNum','createdAt'],
        order: [
            ['id', 'desc']
        ],
        include:[
            {
                model:User,
                attributes:['id','avatar','userName']
            },
            {
                model:DynamicLike,
                attributes:[]
            }
        ],
        where:whereData
        // raw: true
    })
    return result
}

/**
 * @description 更新动态点赞数量
 * @param {*} param0 
 */
async function updateDynamic(like,id) {
    const result = await Dynamic.update({
        likeNum:like == 1 ? Sequelize.literal('likeNum+1') : Sequelize.literal('likeNum-1'),//自增自减
    },{
        where:{
            id
        }
    }
    )
    return result
}

/**
 * @description 查询是否点赞
 * @param {*} param0 
 */
async function getDynamicLike({dynamicId,userId}) {
    const result = await DynamicLike.findOne({
        where:{
            dynamicId,
            userId
        }
    })
    console.log(JSON.stringify(result),'result')
    return result
}

/**
 * @description 创建点赞
 * @param {*} param0 
 */
async function createDynamicLike({dynamicId,userId}) {
    const result = await DynamicLike.create({
        dynamicId,
        userId
    })
    return result
}

/**
 * @description 删除点赞
 * @param {*} param0 
 */
async function deleteDynamicLike({dynamicId,userId}) {
    const result = await DynamicLike.destroy({
        where:{
            dynamicId,
            userId
        }
    })
    return result > 0
}

/**
 * @description  更新动态喜欢数据
 * @param {number} isLike 是否喜欢此动态1喜欢0不喜欢
 */
async function updateDynamicLike({dynamicId,userId,isLike}) {
    const result = await DynamicLike.update({
        isLike
    },{
        where:{
            dynamicId,
            userId
        }
    })
    return result
}

module.exports = {
    createDynamic,
    getDynamicList,
    getDynamicLike,
    createDynamicLike,
    deleteDynamicLike,
    updateDynamic,
    updateDynamicLike
}